package com.working.libcommon.exts

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Rect
import android.view.TouchDelegate
import android.view.View
import android.view.animation.Animation
import android.view.animation.CycleInterpolator
import android.view.animation.TranslateAnimation

/**
 * view 防抖点击
 */
fun View.onClick(delayTimes: Long = 600L, action: (view: View) -> Unit) {
    var locked = false
    this.setOnClickListener {
        if (!locked) {
            locked = true
            action(it)
            it.postDelayed({
                locked = false
            }, delayTimes)
        }
    }
}

/**
 * 对view截屏
 */
fun View.bitmapSnapshot(): Bitmap {
    val screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
    val c = Canvas(screenshot)
    c.translate((-scrollX).toFloat(), (-scrollY).toFloat())
    draw(c)
    return screenshot
}

/**
 * view震动
 */
fun View.shake(): Animation {
    val anim = TranslateAnimation(0f, 0f, 0f, 5f)
    anim.duration = 700
    anim.interpolator = CycleInterpolator(7f)
    startAnimation(anim)
    return anim
}


/**
 * 点击区域扩大
 */
fun View.expandViewTouchDelegate(padding: Int): View {
    (parent as View).post {
        val bounds = Rect()
        isEnabled = true
        getHitRect(bounds)
        bounds.top -= padding
        bounds.bottom += padding
        bounds.left -= padding
        bounds.right += padding

        val touchDelegate = TouchDelegate(bounds, this)
        if (parent is View) {
            (parent as View).touchDelegate = touchDelegate
        }
    }
    return this
}